﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCMusicStore.Models;

namespace MVCMusicStore.Controllers
{
    public class StoreController : Controller
    {
        MusicStoreEntities db = new MusicStoreEntities();

        public ActionResult Index()
        {
            var genres = from genre in db.Genres
                           select genre.Name;
            var viewModel = new MVCMusicStore.ViewModels.StoreIndexViewModel
            {
                NumberOfGenres = genres.Count(),
                Genres = genres.ToList()
            };
            return View(viewModel);
        }
        public ActionResult Browse()
        {
            //using Server.HtmlEncode to prevent users from injecting Javascript into our View with a link like this /Store/Browse?Genre=<script>window.location='http://hackersite.com'</script>.
            string genrename = Server.HtmlEncode(Request.QueryString["genre"]);
            var genre = new Genre
            {
                Name = genrename
            };

            var albums = db.Genres.Include("Albums").Single(g => g.Name == genrename).Albums;

            var viewModel = new MVCMusicStore.ViewModels.StoreBrowseViewModel 
            { 
                Genre=genre,
                Albums=albums.ToList()
            };
            return View(viewModel);
        }
        public ActionResult Details(int albumId)
        {
            var album = db.Albums.Single(a => a.AlbumId == albumId);
            return View(album);
        }
    }
}
